import { UpdateUserInfoDto } from './Dto/updateUser.dto';
import { FindOneByUsername } from './Dto/findOneByUsername.dto';
import { FindAllUserDto } from './Dto/findAll.dto';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateUserDto } from './Dto/createUser.dto';
import { User } from './user.entity';
import { handleSql } from 'src/support/untils/sql';

export type UserListType = {
  list: User[];
  total: number;
};

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}
  async findAll(findAllUserDto: FindAllUserDto): Promise<UserListType> {
    const { page = 1, limit = 10, ...params } = findAllUserDto;
    const where = handleSql(params);
    const result = await this.usersRepository.findAndCount({
      where: where,
      skip: (page - 1) * limit,
      take: limit,
    });

    return {
      list: result[0],
      total: result[1],
    };
  }

  async findOne(findOneByUsername: FindOneByUsername): Promise<User> {
    return this.usersRepository.findOne({
      where: findOneByUsername,
      select: { user_id: true, username: true, password: true },
    });
  }

  async findOneById(user_id: number): Promise<User> {
    return this.usersRepository.findOneById(user_id);
  }

  async createOne(createUserDto: CreateUserDto): Promise<User> {
    const entityDto = this.usersRepository.create({
      isBan: false,
      ...createUserDto,
    });
    return this.usersRepository.save(entityDto);
  }

  async removeUser(ids: number[]): Promise<any> {
    return this.usersRepository.delete(ids);
  }

  async updateUser(updateUserInfoDto: UpdateUserInfoDto): Promise<any> {
    const hasUser = await this.usersRepository.findOneById(
      updateUserInfoDto.user_id,
    );
    if (!hasUser) {
      return;
    }
    const updateInfo = this.usersRepository.merge(hasUser, updateUserInfoDto);
    return this.usersRepository.save(updateInfo);
  }

  async count(): Promise<any> {
    return this.usersRepository.countBy({ isAdmin: false });
  }

  async getTotal() {
    const result = await this.usersRepository.count();
    return result;
  }
}
